import { login } from "@/services/api/user";
import { setToken } from "@/store/user/authSlice";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input } from "antd";
import { useForm } from "antd/es/form/Form";
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

type FieldType = {
  username: string;
  password: string;
};

const LoginForm: React.FC = (props) => {

  const [form] = useForm<FieldType>();

  const dispatch = useDispatch();

  const nav = useNavigate();

  const [loading, setLoading] = useState(false);

  /** 点击登录 */
  async function handleLogin() {
    try {
      // 登录时，button为加载状态
      setLoading(true);
      // 输入项校验
      await form.validateFields();
      // 发送登录请求
      const loginData = await form.getFieldsValue();
      const result = await login(loginData);
      // token状态管理
      dispatch(setToken(result));
      // 跳转首页（跳转后不需要后退）
      nav('/', {replace: true});
    } catch (err) {
      console.log('Failed:', err);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Form form={form}>
      <Form.Item<FieldType>
        name="username"
        rules={[{ required: true, message: "用户名不能为空！" }]}
      >
        <Input 
          prefix={<UserOutlined />} 
          placeholder="请输入您的用户名" 
        />
      </Form.Item>

      <Form.Item<FieldType>
        name="password"
        rules={[{ required: true, message: "密码不能为空！" }]}
      >
        <Input.Password
          prefix={<LockOutlined />}
          placeholder="请输入您的密码"
        />
      </Form.Item>

      <Form.Item>
        <Button 
          type="primary"
          style={{ width: "100%" }}
          loading={loading}
          onClick={handleLogin}
        >
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default LoginForm;
